using System;
using System.Collections.Generic;
using NHibernate;
using Model;

namespace Infrastructure
{
    public class UnitOfWork : IDisposable, Infrastructure.IUnitOfWork
    {

        private ISession context;
        private ITransaction transaction;
        private BorrowerRepository borrowerRepository;
        private bool _complete;

        public BorrowerRepository BorrowerRepository
        {
            get
            {
                if (borrowerRepository == null)
                {
                    borrowerRepository = new BorrowerRepository(context);
                }
                return borrowerRepository;
            }

        }
        public UnitOfWork()
        {
            context = SessionProvider.GetCurrentSession();
            transaction = context.BeginTransaction();
        }
        

        public void SetComplete()
        {
            _complete = true;
        }
        
        public void Flush()
        {
            context.Flush();
        }

        public void Dispose()
        {
            if (_complete)
            {
                try
                {
                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }
            else
            {
                transaction.Rollback();
            }
        }
    }


    public class TestUnitOfWork : IDisposable, Infrastructure.IUnitOfWork
    {

        private ISession context;
        private ITransaction transaction;
        private BorrowerRepository borrowerRepository;
        private bool _complete;

        public BorrowerRepository BorrowerRepository
        {
            get
            {
                if (borrowerRepository == null)
                {
                    borrowerRepository = new BorrowerRepository(context);
                }
                return borrowerRepository;
            }

        }
        public TestUnitOfWork()
        {
            context = SessionProvider.GetCurrentSession();
            transaction = context.BeginTransaction();
        }


        public void SetComplete()
        {
            _complete = true;
        }

        public void Flush()
        {
            context.Flush();
        }

        public void Dispose()
        {
            if (_complete)
            {
                try
                {
                    transaction.Rollback();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }
            else
            {
                transaction.Rollback();
            }
        }
    }
}
